package com.miaosha.controller;

import com.miaosha.error.EnumError;
import com.miaosha.error.ErrorException;
import com.miaosha.model.viewobject.UserVO;
import com.miaosha.model.UserInformationModel;
import com.miaosha.response.CommonResponse;
import com.miaosha.service.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

@Controller()
@RequestMapping("/user")
public class UserController extends BaseController{


    @Autowired
    private UserService userService;


    @Autowired
    private HttpServletRequest httpServletRequest;


    @RequestMapping(value = "/login", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORM})
    @ResponseBody
    public CommonResponse validateLogin(@RequestParam(name = "mobile")String mobile,
                                   @RequestParam(name = "password")String password) throws ErrorException, UnsupportedEncodingException, NoSuchAlgorithmException {

        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
            throw new ErrorException(EnumError.PARAMETER_VALIDATION_ERROR);
        }

        // 用户登录验证
        String encryptPassword = encodeByMD5(password);
        UserInformationModel userInformationModel = userService.validateLogin(mobile, encryptPassword);

        // 将登录凭证加入用户成功的session
        this.httpServletRequest.getSession().setAttribute("IS_LOGIN", true);
        this.httpServletRequest.getSession().setAttribute("LOGIN_USER", userInformationModel);
        return CommonResponse.create(null);
    }



    @RequestMapping(value = "/register", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORM})
    @ResponseBody
    public CommonResponse register(@RequestParam(name = "mobile")String mobile,
                                   @RequestParam(name = "otpCode")String otpCode,
                                   @RequestParam(name = "userName")String userName,
                                   @RequestParam(name = "userAge")Integer userAge,
                                   @RequestParam(name = "userGender")Integer userGender,
                                   @RequestParam(name = "password")String password) throws ErrorException, UnsupportedEncodingException, NoSuchAlgorithmException {
        // 验证手机号和otpCode相符合
        String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(mobile);
        if (!StringUtils.equals(otpCode, inSessionOtpCode)){
            throw new ErrorException(EnumError.PARAMETER_VALIDATION_ERROR,"短信验证码不正确");
        }

        // 用户注册流程
        UserInformationModel userInformationModel = new UserInformationModel();
        userInformationModel.setMobile(mobile);
        userInformationModel.setName(userName);
        userInformationModel.setAge(userAge);
        userInformationModel.setGender(userGender);
        userInformationModel.setName(userName);
        userInformationModel.setRegisterMode(1);
        userInformationModel.setEncryptPassword(this.encodeByMD5(password));

        userService.register(userInformationModel);
        return CommonResponse.create(null);
    }

    private String encodeByMD5(String text) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        byte[] bytes = text.getBytes("UTF-8");
        String result = base64Encoder.encode(bytes);
        return result;
    }


    @RequestMapping(value = "/getOtp", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORM})
    @ResponseBody
    public CommonResponse getOTP(@RequestParam(name = "mobile")String mobile) throws ErrorException {
        if (mobile == null || mobile.isEmpty()){
            throw new ErrorException(EnumError.PARAMETER_VALIDATION_ERROR) ;
        }
        // 按照一定规则生成otp验证码
        Random random = new Random();
        int randomInt = random.nextInt(999999);
        String otpCode = String.valueOf(randomInt);

        // 将otp验证码对应用户手机号码
        httpServletRequest.getSession().setAttribute(mobile, otpCode);

        // 将otp发送给用户
        System.out.println("mobile = " + mobile + " & otpCode = " + otpCode);

        return CommonResponse.create(null);
    }


    @RequestMapping("/get")
    @ResponseBody
    public CommonResponse getUser(@RequestParam(name = "id")Integer id) throws ErrorException {
        // 调用service服务获取对应id用户返回前端
        UserInformationModel userModel = userService.getUserById(id);

        // 用户不存在
        if (userModel == null){
            throw new ErrorException(EnumError.USER_NOT_EXIST) ;
        }

        UserVO userVO = convertFromUserModel(userModel);
        // 返回通用类型
        return CommonResponse.create(userVO);
    }

    private UserVO convertFromUserModel(UserInformationModel userInformationModel){
        if (userInformationModel == null) return null;
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userInformationModel, userVO);
        return userVO;
    }


}
